import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { ElectronModule } from '@doubleshot/nest-electron'
import { is } from '@electron-toolkit/utils'
import { Module } from '@nestjs/common'
import { ConfigService, ConfigModule } from '@nestjs/config'
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm'
import { shell, BrowserWindow, app } from 'electron'
import { parse } from 'yaml'
import icon from '../../resources/icon.png?asset'
import { AppController } from './app.controller'
import { configFile } from './common/constants/path'
import { UserModule } from './modules/user/user.module'

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    minWidth: 900,
    minHeight: 670,
    // resizable: false,
    show: false,
    autoHideMenuBar: true,
    frame: false,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false,
    },
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)

    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env.ELECTRON_RENDERER_URL) {
    mainWindow.loadURL(process.env.ELECTRON_RENDERER_URL)
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  mainWindow.on('maximize', () => {
    mainWindow.webContents.send('maximize')
  })

  mainWindow.on('unmaximize', () => {
    mainWindow.webContents.send('unmaximize')
  })

  return { win: mainWindow }
}

@Module({
  imports: [
    ElectronModule.registerAsync({
      isGlobal: true,
      useFactory: () => createWindow(),
    }),
    // 配置模块
    ConfigModule.forRoot({
      cache: true,
      load: [() => parse(readFileSync(configFile, 'utf8'))],
      isGlobal: true,
    }),
    // 数据库
    TypeOrmModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => {
        const config = configService.get('db.sqlite')

        return {
          type: 'sqlite',
          autoLoadEntities: true,
          keepConnectionAlive: true,
          ...config,
          database: join(app.getPath('userData'), config.database),
        } as TypeOrmModuleOptions
      },
    }),
    UserModule,
  ],
  controllers: [AppController],
  providers: [],
})
export class AppModule {}
